# -*- coding: utf-8 -*-

from django import forms
from student.models import EnrollmentSheet
from exams.models import Exam, Professor, SubjectYear, Subject, Executor
from core.models import Post
import datetime
from django.conf import settings
from django.core.exceptions import ValidationError

class ExecutorForm(forms.ModelForm):
  subject = forms.ModelChoiceField(queryset = Subject.objects.all(), label = u'Predmet')
  year = forms.ChoiceField(label = u'Šolsko leto')
  group = forms.ChoiceField(label = u'Skupina izvajalcev')
  
  class Meta:
    model = Executor
    fields = ('professor',)
  
  def __init__(self, *args, **kwargs):
    super(ExecutorForm, self).__init__(*args, **kwargs)
    
    # Make sure the list is remade
    if self.instance.pk:
      self.fields['group'].choices = tuple([('new', '---')] + list(Executor.get_all_groups(True)))
    else:
      self.fields['group'].choices = tuple([('new', '---')] + list(Executor.get_all_groups(True)))
    self.fields['year'].choices = reversed(EnrollmentSheet.get_all_years(False))
    
    # Populate the fields
    if self.instance.pk:
      self.fields['subject'].initial = self.instance.subject_year.subject
      self.fields['year'].initial = self.instance.subject_year.school_year(True)
      cooperates = self.instance.cooperates_with if self.instance.cooperates_with else self.instance
      self.fields['group'].initial = '{0}-{1}-{2}'.format(cooperates.pk,
                                                          self.instance.subject_year.subject.pk,
                                                          self.instance.subject_year.school_year(True))
  
  def clean(self):
    def group_existance(head, new_professor):
      groups = [set([j.pk for j in i.cooperates_with_professors()]) for i in Executor.objects.filter(subject_year = head.subject_year, cooperates_with__isnull = True)]
      new_group = set([i.pk for i in head.cooperates_with_professors() + [new_professor]])
      return new_group in groups
    
    cleaned_data = {}
    # Copy the professor
    cleaned_data['professor'] = self.cleaned_data['professor']
    
    # Make the proper queries and connections
    cleaned_data['subject_year'] = SubjectYear.objects.get(subject = self.cleaned_data['subject'], school_year_start = int(self.cleaned_data['year'][:4]))
    
    if 'group' in self.cleaned_data and self.cleaned_data['group'] != 'new':
      head = Executor.objects.get(pk = self.cleaned_data['group'].split('-')[0])
    else:
      head = None
    
    existance_check = Executor.objects.filter(professor = cleaned_data['professor'], subject_year = cleaned_data['subject_year'], cooperates_with__isnull = True)
    
    if head and head != self.instance:
      # Check if he is already inside selected group
      if cleaned_data['professor'] in head.cooperates_with_professors():
        self._errors['group'] = self.error_class([u'Profesor je že v izbrani skupini izvajalcev.'])
      elif group_existance(head, cleaned_data['professor']):
        self._errors['group'] = self.error_class([u'Permutacija profesorjev že izvaja ta predmet.'])
      else:
        cleaned_data['cooperates_with'] = head
    elif existance_check.exists() and self.instance not in existance_check:
      if set([cleaned_data['professor'].pk]) in [set([j.pk for j in i.cooperates_with_professors()]) for i in existance_check]:
        self._errors['group'] = self.error_class([u'Profesor že izvaja ta predmet.'])
    return cleaned_data
  
  def save(self, commit = True):
    """Because we completely changed the logic of this form, we have to completely change it's save method.
    """
    executor = self.instance
    executor.professor = self.cleaned_data['professor']
    executor.subject_year = self.cleaned_data['subject_year']
    executor.cooperates_with = self.cleaned_data['cooperates_with'] if 'cooperates_with' in self.cleaned_data else None
    
    if commit is True:
      executor.save()
    return executor
  
  def save_m2m(self):
    """Just ignore it :)
    """
    pass

class ExamFormApplication(forms.Form):
  
  exam_query = SubjectYear.objects.none()  
  #create form
  exam = forms.ModelChoiceField(exam_query, label = "Predmet")
  date = forms.ChoiceField(label = "Izpitni rok")
  
class ExamForm(forms.ModelForm):

  def __init__(self, *args, **kwargs):
    subject = kwargs.pop('subject', None)
    professor = kwargs.pop('professor', None)
    super(ExamForm, self).__init__(*args, **kwargs)
    if subject:
      pchoices = subject.executors_choices()
      print "Izbire: ",pchoices
      if professor:
        pchoices_tmp = []
        for (k,v) in pchoices:
          if unicode(v).find(unicode(professor)) > -1:
            pchoices_tmp.append((k,v))
        pchoices = pchoices_tmp
      self.fields["executor"] = forms.ChoiceField(label=u'Izvajalec', choices=pchoices);
     
  def clean(self):
    cleaned_data = self.cleaned_data
    if cleaned_data.has_key('executor') and int(cleaned_data['executor']) > 0:
      cleaned_data['executor'] = Executor.objects.get(pk=cleaned_data['executor'])
    return cleaned_data

  class Meta:
    model = Exam
  
class CardListSelection(forms.Form):
  PART_GRADE_CHOICES = (
    ("1","Vsa polaganja"),
    ("2","Zadnje polaganje")
  )
  view = forms.ChoiceField(choices=PART_GRADE_CHOICES,label="Pogled")
  program = forms.ChoiceField(choices=[],label="Študijski program")
  
  def __init__(self, *args, **kwargs):
    self.student = kwargs.pop('student')
    super(forms.Form, self).__init__(*args, **kwargs)
    self.fields['program'].choices = self.student.get_all_programs(True)
  
class ExamSelection(forms.Form):
  exam = forms.ModelChoiceField(queryset = Exam.objects.all().order_by('-date'), empty_label="(ni izbrano)", label = "Izpit")

class InputExamSelection(forms.Form):
  subject = forms.ModelChoiceField(queryset = SubjectYear.objects.all().order_by('subject'), empty_label="(nothing)", label = "Predmet")
  examDate = forms.DateField(initial=datetime.date.today(), label="Datum izpita")
  examTime = forms.TimeField(initial=datetime.time, label="Ura izpita")
  howMany = forms.IntegerField(initial=100, min_value=1, label="Omejitev vpisa")
  positive = forms.IntegerField(initial=50, min_value=1, label="Meja za pozitivno")
  max = forms.IntegerField(initial=100, min_value=1, label="Maksimalno število točk")
  place = forms.CharField(initial="", label="Učilnica")
  rating_type = forms.ChoiceField(choices = settings.RATE_TYPES,label="Tip ocene")
  executor = forms.ModelChoiceField(queryset = Executor.objects.all().order_by('professor'), empty_label="(nothing)", label = "Izvajalec")

class ViewExams(forms.Form):
  ALL_EXAMS_CHOICES = (
    ("1","Vsi izpiti"),
    ("2","Samo neopravljeni izpiti")                   
  )
  
  year = forms.ChoiceField(choices = settings.STUDENT_YEARS, label="Letnik")
  all_exams = forms.ChoiceField(choices = ALL_EXAMS_CHOICES, label="Izpiti")
